﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Caching;
using System.Web;

namespace Xmobile.BO
{
    public class SQLCache
    {
        public static class CacheNameFormat
        {
            public static string ContentCrawler_Select_by_CatID(int CatID)
            {
                return "ContentCrawler_Select_by_CatID_" + CatID.ToString();
            }

            public static string Apps_Select_by_CatID(int CatID)
            {
                return "Apps_Select_by_CatID_" + CatID.ToString();
            }
            public static string Apps_Select_List_Padding(int CatID, int PageIndex, int PageSize)
            {
                return "Apps_Select_List_Padding_" + CatID.ToString() + "_" + PageIndex.ToString() + "_" + PageSize.ToString();
            }

            public static string Category_Select_by_CatID(int CatID)
            {
                return "Category_Select_by_CatID_" + CatID;
            }

            public static string Apps_Select_by_AppID(int AppID)
            {
                return "Apps_Select_by_AppID_" + AppID;
            }
        }

        #region Cache methods
        public static void SaveToCacheDependency(string database, string tableName, string cacheName, object data)
        {
            SqlCacheDependency sqlDep = new SqlCacheDependency(database, tableName);
            HttpContext.Current.Cache.Insert(cacheName, data, sqlDep);
        }
        public static void SaveToCacheDependency(string database, string[] tableName, string cacheName, object data)
        {
            AggregateCacheDependency aggCacheDep = new AggregateCacheDependency();
            SqlCacheDependency[] sqlDepGroup = new SqlCacheDependency[tableName.Length];
            for (int i = 0; i < tableName.Length; i++)
            {
                sqlDepGroup[i] = new SqlCacheDependency(database, tableName[i]);

            }
            aggCacheDep.Add(sqlDepGroup);
            HttpContext.Current.Cache.Insert(cacheName, data, aggCacheDep);
        }
        public static T GetFromCacheDependency<T>(string cacheName)
        {
            object data = HttpContext.Current.Cache[cacheName];
            if (null != data)
            {
                try
                {
                    return (T)data;
                }
                catch
                {
                    return default(T);
                }
            }
            else
            {
                return default(T);
            }
        }
        
        #endregion
    }
}
